package com.xunxi.mimi.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.AnimationDrawable;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

import com.xunxi.mimi.app_base.R;


/**
 * 作者: liyu on  2018/1/2 0002 15:06
 * 功能描述:
 * 备注:
 */
public class LoadingProgressBar extends AppCompatImageView {

    private AnimationDrawable mAnimation;
    private boolean mPaused = false;

    public LoadingProgressBar(Context context) {
        this(context, null, 0);
    }

    public LoadingProgressBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LoadingProgressBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ProgressBarView);
        int resourceId = array.getResourceId(R.styleable.ProgressBarView_frame_drawable, -1);
        setImageResource(resourceId);
        mPaused = array.getBoolean(R.styleable.ProgressBarView_frame_paused, false);
        array.recycle();

        if (mAnimation == null){
            mAnimation = (AnimationDrawable) getDrawable();
        }
        beginAnim();
    }

    public void stopAnim() {
        if (mAnimation != null && mAnimation.isRunning()) {
            mAnimation.stop();
        }
    }

    public void beginAnim() {
        if (!mPaused && mAnimation != null && !mAnimation.isRunning()) {
            mAnimation.start();
        }
    }

    @Override
    protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);

        if (visibility == View.VISIBLE){
            beginAnim();
        }else {
            stopAnim();
        }
    }
}
